//
//  GCMSBCaoZuoViewController.m
//  GeeCityManager
//
//  Created by 聚城科技 on 16/11/16.
//  Copyright © 2016年 聚城科技. All rights reserved.
//

#import "GCMSBCaoZuoViewController.h"
#import "AJPhotoPickerViewController.h"
#import "QRadioButton.h"
#import "UITextView+placeholder.h"
#import "GCMSheBeiRequst.h"

//图片相关的库的头文件
#import "AJPhotoPickerViewController.h"
#import <AVFoundation/AVFoundation.h>
#import <MobileCoreServices/MobileCoreServices.h>
#import "AJPhotoBrowserViewController.h"

@interface GCMSBCaoZuoViewController ()<UIScrollViewDelegate>

//照片
@property (strong, nonatomic) NSMutableArray *photos;
@property (strong, nonatomic) NSMutableArray *ceamePhotos;
@property (strong, nonatomic) NSMutableArray *scPhotos;
@property (strong, nonatomic) NSMutableString *photoStr;
@end

@implementation GCMSBCaoZuoViewController{

    UIScrollView *_imageScrollV;
    QRadioButton *_zl1;
    QRadioButton *_zl2;
    UITextView *textV;
    UIView * _bgView;
}

-(void)viewWillAppear:(BOOL)animated{

    self.scPhotos = [[NSMutableArray alloc]init];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self createUI];
    [self createImageScrollView];

}


-(void)createUI{

    self.view.backgroundColor = [UIColor colorWithRed:0.96 green:0.96 blue:0.96 alpha:1];
    UILabel *label1 = [[UILabel alloc]initWithFrame:CGRectMake(20, 70, 50, 30)];
    label1.text = @"类型:";
    label1.textColor = [UIColor lightGrayColor];
    [self.view addSubview:label1];
    UILabel *typelabel1 = [[UILabel alloc]initWithFrame:CGRectMake(70, 70, 50, 30)];
    typelabel1.textColor = [UIColor colorWithRed:0.09 green:0.64 blue:0.58 alpha:1];
    typelabel1.text = self.type;
    [self.view addSubview:typelabel1];
    
    
    UILabel *label2 = [[UILabel alloc]initWithFrame:CGRectMake(20, 110, 50, 30)];
    label2.text = @"情况:";
    label2.textColor = [UIColor lightGrayColor];
    [self.view addSubview:label2];
    //情况
    _zl1 = [[QRadioButton alloc] initWithDelegate:self groupId:@"groupId1"];
    _zl1.frame = CGRectMake(80, 110, 100, 30);
    [_zl1 setTitle:@"正常" forState:UIControlStateNormal];
    [_zl1 setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    [_zl1.titleLabel setFont:[UIFont boldSystemFontOfSize:15.0f]];
    [self.view addSubview:_zl1];
    [_zl1 setChecked:YES];
    _zl2 = [[QRadioButton alloc] initWithDelegate:self groupId:@"groupId1"];
    _zl2.frame = CGRectMake( 180, 110, 100, 30);
    [_zl2 setTitle:@"异常" forState:UIControlStateNormal];
    [_zl2 setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    [_zl2.titleLabel setFont:[UIFont boldSystemFontOfSize:15.0f]];
    [self.view addSubview:_zl2];
    
    _bgView = [[UIView alloc]initWithFrame:CGRectMake(20, 150, SCREEN_WIDTH - 40, SCREEN_WIDTH - 40)];
    _bgView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_bgView];
    textV = [[UITextView alloc]initWithFrame:CGRectMake(0, 0, _bgView.bounds.size.width, _bgView.bounds.size.width - 100)];
    textV.font = [UIFont systemFontOfSize:14]; //注意先设置字体,再设置placeholder
    textV.placeholder = @"请填写内容";
    [_bgView addSubview:textV];
    
    //    获取图片
    UIButton *button = [[UIButton alloc]init];
    button.frame = CGRectMake(0, _bgView.bounds.size.width - 60, 60, 60) ;
    [button setImage:[UIImage imageNamed:@"btn_app_pic"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(imageGet) forControlEvents:UIControlEventTouchUpInside];
    [_bgView addSubview:button];
    
    UIButton *subButton = [[UIButton alloc]initWithFrame:CGRectMake(SCREEN_WIDTH /4, SCREEN_HEIGHT - 60, SCREEN_WIDTH /2, 40)];
    subButton.backgroundColor = [UIColor colorWithRed:0.25 green:0.44 blue:0.63 alpha:1];
    [subButton setTitle:@"提交" forState:UIControlStateNormal];
    [subButton addTarget:self action:@selector(subMessage) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:subButton];
    
}
-(void)subMessage{
    
    NSMutableDictionary *parameters= [[NSMutableDictionary alloc]init];
    parameters[@"id"] = self.sbid;
    parameters[@"type"] = self.type;
    if (_zl1.selected) {
        parameters[@"state"] = @"正常";
    }else{
        parameters[@"state"] = @"异常";
    }
    parameters[@"content"] = textV.text;
    parameters[@"userId"] = [GCMUserInfo instance].uid;
    parameters[@"username"] = [GCMUserInfo instance].realName;
    for (UIImageView *imageV in _imageScrollV.subviews) {
        NSData *data = UIImageJPEGRepresentation(imageV.image, 0.4);
        NSString* encodeResult = [data base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
        if (encodeResult) {
            [self.scPhotos addObject:encodeResult];
        }else{
    
        }
    }
    NSString * substr = [self.scPhotos componentsJoinedByString:@","];
    parameters[@"images"] = substr;
    [GCMSheBeiRequst postSheBeiDataWithParmerts:parameters WithUrl:SHEBSUBPLAN_URL Success:^(id obj, NSError *err) {
        if ([obj valueForKey:@"success"]) {
            [ProgressHUD showSuccess:[obj valueForKey:@"data"]];
            [self.navigationController popViewControllerAnimated:YES];
        }else{
            [ProgressHUD showError:[obj valueForKey:@"message"]];
        }
    }];
}

-(void)createImageScrollView{
    //    创建可以滑动的视图
    _imageScrollV = [[UIScrollView alloc]initWithFrame:CGRectMake(60, _bgView.bounds.size.width - 100, _bgView.bounds.size.width - 60, 100)];
    _imageScrollV.delegate = self;
    _imageScrollV.alwaysBounceHorizontal = NO;
    _imageScrollV.alwaysBounceVertical = NO;
    _imageScrollV.showsHorizontalScrollIndicator = NO;
    _imageScrollV.showsVerticalScrollIndicator = NO;
    _imageScrollV.bounces = NO;
    _imageScrollV.contentOffset = CGPointMake(0, 0);
    _imageScrollV.contentSize = CGSizeMake(SCREEN_WIDTH, 50);
    _imageScrollV.backgroundColor = [UIColor whiteColor];
    self.automaticallyAdjustsScrollViewInsets = NO;
    [_bgView addSubview:_imageScrollV];
    
    
}


////////////////////////////获取图片//////////////////////////////////////
-(void)imageGet{
    
    AJPhotoPickerViewController *picker = [[AJPhotoPickerViewController alloc] init];
    picker.maximumNumberOfSelection = 15;
    picker.multipleSelection = YES;
    picker.assetsFilter = [ALAssetsFilter allPhotos];
    picker.showEmptyGroups = YES;
    picker.delegate = self;
    picker.selectionFilter = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
        return YES;
    }];
    [self presentViewController:picker animated:YES completion:nil];
    //NSLog(@"ppppppic%@",self.photos);
}
#pragma mark - BoPhotoPickerProtocol
- (void)photoPickerDidCancel:(AJPhotoPickerViewController *)picker {
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)photoPicker:(AJPhotoPickerViewController *)picker didSelectAssets:(NSArray *)assets {
    [self.photos addObjectsFromArray:assets];
    CGFloat x = 0;
    CGRect frame = CGRectMake(0, 0, 100, 100);
    if (self.ceamePhotos.count == 0) {
        for (int i = 0 ; i < self.photos.count; i++) {
            ALAsset *asset = self.photos[i];
            UIImage *tempImg = [UIImage imageWithCGImage:asset.defaultRepresentation.fullScreenImage];
            frame.origin.x = x;
            UIImageView *imageView = [[UIImageView alloc] initWithFrame:frame];
            [imageView setContentMode:UIViewContentModeScaleAspectFill];
            imageView.clipsToBounds = YES;
            imageView.image = tempImg;
            imageView.tag = i;
            imageView.userInteractionEnabled = YES;
            [imageView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showBig:)]];
            [_imageScrollV addSubview:imageView];
            x += frame.size.width+5;
        }
        
    } else {
        //[self.photos addObjectsFromArray:self.ceamePhotos];
        for (int i = 0 ; i < self.photos.count; i++) {
            frame.origin.x = 105 *self.ceamePhotos.count + x;
            ALAsset *asset = self.photos[i];
            UIImage *tempImg = [UIImage imageWithCGImage:asset.defaultRepresentation.fullScreenImage];
            UIImageView *imageVie = [[UIImageView alloc] initWithFrame:frame];
            [imageVie setContentMode:UIViewContentModeScaleAspectFill];
            imageVie.clipsToBounds = YES;
            imageVie.image = tempImg;
            imageVie.userInteractionEnabled = YES;
            [imageVie addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showBig:)]];
            [_imageScrollV addSubview:imageVie];
            x += frame.size.width+5;
        }
    }
    _imageScrollV.contentSize = CGSizeMake(105 * (self.photos.count +self.ceamePhotos.count) - 5, 0);
    [picker dismissViewControllerAnimated:NO completion:nil];
    
}

- (void)photoPicker:(AJPhotoPickerViewController *)picker didSelectAsset:(ALAsset *)asset {
    NSLog(@"%s",__func__);
}

- (void)photoPicker:(AJPhotoPickerViewController *)picker didDeselectAsset:(ALAsset *)asset {
    NSLog(@"%s",__func__);
}

//超过最大选择项时
- (void)photoPickerDidMaximum:(AJPhotoPickerViewController *)picker {
    NSLog(@"%s",__func__);
}

//低于最低选择项时
- (void)photoPickerDidMinimum:(AJPhotoPickerViewController *)picker {
    NSLog(@"%s",__func__);
}

- (void)photoPickerTapCameraAction:(AJPhotoPickerViewController *)picker {
    [self checkCameraAvailability:^(BOOL auth) {
        if (!auth) {
            NSLog(@"没有访问相机权限");
            return;
        }
        [picker dismissViewControllerAnimated:NO completion:nil];
        UIImagePickerController *cameraUI = [UIImagePickerController new];
        cameraUI.allowsEditing = NO;
        cameraUI.delegate = self;
        cameraUI.sourceType = UIImagePickerControllerSourceTypeCamera;
        cameraUI.cameraFlashMode=UIImagePickerControllerCameraFlashModeAuto;
        
        [self presentViewController: cameraUI animated: YES completion:nil];
    }];
}

#pragma mark - AJPhotoBrowserDelegate


- (void)photoBrowser:(AJPhotoBrowserViewController *)vc deleteWithIndex:(NSInteger)index {
    NSLog(@"%s",__func__);
    
    long i = self.photos.count - 1;
    _imageScrollV.contentSize = CGSizeMake(105 * i - 5, 0);
    i--;
    //    if (i) {
    //        [_imageScrollV removeFromSuperview];
    //    }
    
}

- (void)photoBrowser:(AJPhotoBrowserViewController *)vc didDonePhotos:(NSArray *)photos {
    NSLog(@"%s",__func__);
    [self.photos removeAllObjects];
    [self.photos addObjectsFromArray:photos];
    
    for (UIView *view in _imageScrollV.subviews) {
        [view removeFromSuperview];
    }
    CGFloat x = 0;
    CGRect frame = CGRectMake(0, 0, 100, 100);
    for (int i = 0 ; i < self.photos.count; i++) {
        ALAsset *asset = self.photos[i];
        UIImage *tempImg = [UIImage imageWithCGImage:asset.defaultRepresentation.fullScreenImage];
        frame.origin.x = x;
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:frame];
        [imageView setContentMode:UIViewContentModeScaleAspectFill];
        imageView.clipsToBounds = YES;
        imageView.image = tempImg;
        NSData *data = UIImageJPEGRepresentation(tempImg, 0.4);
        NSString* encodeResult = [data base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
        if (encodeResult) {
            
            [self.scPhotos addObject:encodeResult];
            //NSLog(@"ppppppic%@",self.photos);
        }else{
            // [self.photos addObject:data];
        }
        
        imageView.tag = i;
        imageView.userInteractionEnabled = YES;
        [imageView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showBig:)]];
        [_imageScrollV addSubview:imageView];
        x += frame.size.width+5;
    }
    
    _imageScrollV.contentSize = CGSizeMake(105 * self.photos.count - 5, 0);
    [vc dismissViewControllerAnimated:YES completion:nil];
    // NSLog(@"ppppppic%@",self.photos);
    
}

- (void)showBig:(UITapGestureRecognizer *)sender {
    NSInteger index = sender.view.tag;
    AJPhotoBrowserViewController *photoBrowserViewController = [[AJPhotoBrowserViewController alloc] initWithPhotos:self.photos index:index];
    photoBrowserViewController.delegate = self;
    [self presentViewController:photoBrowserViewController animated:YES completion:nil];}

#pragma mark - UIImagePickerDelegate
- (void)imagePickerControllerDidCancel:(UIImagePickerController *) picker {
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)image:(UIImage*)image didFinishSavingWithError:(NSError*)error contextInfo:(void*)contextInfo {
    if (!error) {
        NSLog(@"保存到相册成功");
    }else{
        NSLog(@"保存到相册出错%@", error);
    }
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    NSString *mediaType = [info objectForKey: UIImagePickerControllerMediaType];
    UIImage *originalImage;
    if (CFStringCompare((CFStringRef) mediaType,kUTTypeImage, 0)== kCFCompareEqualTo) {
        originalImage = (UIImage *) [info objectForKey:UIImagePickerControllerOriginalImage];
    }
    //    self.imageView.image = originalImage;
    [self.ceamePhotos addObject:originalImage];
    NSLog(@"%@",self.ceamePhotos);
    CGFloat x = 0;
    CGRect frame = CGRectMake(0, 0, 100, 100);
    if (self.photos.count == 0) {
        for (int i = 0 ; i < self.ceamePhotos.count; i++) {
            frame.origin.x = x;
            UIImageView *imageView = [[UIImageView alloc] initWithFrame:frame];
            [imageView setContentMode:UIViewContentModeScaleAspectFill];
            imageView.clipsToBounds = YES;
            imageView.image = self.ceamePhotos[i];
            //        imageView.tag = i;
            imageView.userInteractionEnabled = YES;
            [imageView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showBig:)]];
            [_imageScrollV addSubview:imageView];
            x += frame.size.width+5;
        }
    }else{
        NSLog(@"%ld",self.ceamePhotos.count);
        for (int i = 0 ; i < self.ceamePhotos.count; i++) {
            frame.origin.x = 105 *(self.photos.count+self.ceamePhotos.count - 1);
            UIImageView *imageView = [[UIImageView alloc] initWithFrame:frame];
            [imageView setContentMode:UIViewContentModeScaleAspectFill];
            imageView.clipsToBounds = YES;
            imageView.image = self.ceamePhotos[i];
            //        imageView.tag = i;
            imageView.userInteractionEnabled = YES;
            [imageView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showBig:)]];
            [_imageScrollV addSubview:imageView];
            x += frame.size.width+5;
        }
    }
    _imageScrollV.contentSize = CGSizeMake(105 * (self.photos.count+self.ceamePhotos.count), 0);
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
}

- (void)checkCameraAvailability:(void (^)(BOOL auth))block {
    BOOL status = NO;
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if(authStatus == AVAuthorizationStatusAuthorized) {
        status = YES;
    } else if (authStatus == AVAuthorizationStatusDenied) {
        status = NO;
    } else if (authStatus == AVAuthorizationStatusRestricted) {
        status = NO;
    } else if (authStatus == AVAuthorizationStatusNotDetermined) {
        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
            if(granted){
                if (block) {
                    block(granted);
                }
            } else {
                if (block) {
                    block(granted);
                }
            }
        }];
        return;
    }
    if (block) {
        block(status);
    }
}

- (NSMutableArray *)photos {
    if (_photos == nil) {
        _photos = [NSMutableArray array];
    }
    return _photos;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
